package fms.services.impls;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import fms.common.FieldInfo;
import fms.services.FieldQueryService;
import fms.services.ServiceException;
import fms.services.impls.tables.TableNameConsts;
import fms.services.impls.tables.FieldTableConsts;
import fms.services.persistence.ConnectionFactory;
import fms.services.persistence.ConnectionTool;

public class FieldQueryServiceImpl implements FieldQueryService {

	private Logger log = Logger.getLogger(FieldQueryServiceImpl.class.getName());
	
	private static String getFieldInfoById_SQL = "SELECT * FROM "
		+ TableNameConsts.TABLE_FIELDINFO + " WHERE " + FieldTableConsts.FIELD_ID + "=?";
	
	public FieldInfo getFieldInfoById(String field_id) throws ServiceException {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		conn = ConnectionFactory.getFactory().getConnection();
		String sql = getFieldInfoById_SQL;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1,field_id);
			rs=ps.executeQuery();
			List<FieldInfo> infos = buildFieldInfo(rs);
			if (infos.size() > 0) {
				return infos.get(0);
			}
		}
		catch (SQLException e) {
			e.printStackTrace();
			log.log(Level.SEVERE, "get field by field_id failed! " + field_id);
			throw new ServiceException(
					ServiceException.SERVICE_EXCUTING_EXCEPTION_DBERROR,
			"get field by field_id failed!");
		} finally {
			ConnectionTool.closeConnection(conn, ps, null);
		}
		return null;
	}

	private List<FieldInfo> buildFieldInfo(ResultSet rs) throws SQLException{
		ArrayList<FieldInfo> al = new ArrayList<FieldInfo>();
		while (rs.next()) {
			FieldInfo info = new FieldInfo();
			info.setFieldId(rs.getString(FieldTableConsts.FIELD_ID));
			info.setFieldType(rs.getInt(FieldTableConsts.FIELD_TYPE));
			info.setFieldCapacity(rs.getInt(FieldTableConsts.FIELD_CAPACITY));
			info.setFieldPrice(rs.getDouble(FieldTableConsts.FIELD_PRICE));
			
			al.add(info);
		}
		return al;
	}

	public String getServiceName() {
		return "Field Query Service Implementation";
	}

	public String getServiceVersion() {
		return "1.0";
	}
	
	public static void main(String[] args) {
		FieldQueryServiceImpl uqs = new FieldQueryServiceImpl();
		FieldInfo fieldinfo = new FieldInfo();
		try {
			fieldinfo = uqs.getFieldInfoById("wan");
		} catch (ServiceException e) {
			
			e.printStackTrace();
		}
		System.out.println(fieldinfo.getFieldId() + " " + fieldinfo.getFieldType() + " " + fieldinfo.getFieldCapacity() + " " + fieldinfo.getFieldPrice()) ;
		
	}

	
}
